package cool.capturer.android.capturer;

import android.Manifest;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.util.AttributeSet;

import cool.capturer.android.capturer.constant.Constant;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

public class CameraView extends GLSurfaceView {

    protected VideoManager mVideoManager;

    protected boolean mIsFrontCamera = false;

    public CameraView(Context context) {
        super(context);
        init(context);
    }

    public CameraView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public void init(Context context) {
        mVideoManager = VideoManager.createInstance(context);
        mVideoManager.allocate(1920, 1080, 30, mIsFrontCamera ? Constant.CAMERA_FACING_FRONT : Constant.CAMERA_FACING_BACK);
        mVideoManager.setRenderView(this);
    }

    public void onResume() {
        if (mVideoManager != null) {
            mVideoManager.startCapture();
        }
    }

    public void onPause() {
        if (mVideoManager != null) {
            mVideoManager.stopCapture();
        }
    }

    public void switchCamera() {
        if (mVideoManager != null) {
            mVideoManager.switchCamera();
        }
    }

    /**
     * 开始
     */
    public void start() {
        if (mVideoManager != null) {
            mVideoManager.allocate(1920, 1080, 30, mIsFrontCamera ? Constant.CAMERA_FACING_FRONT : Constant.CAMERA_FACING_BACK);
            mVideoManager.startCapture();
        }
    }

    /**
     * 释放资源
     */
    public void release() {
        if (mVideoManager != null) {
            mVideoManager.stopCapture();
            mVideoManager.deallocate();
        }
    }

    /**
     * 是否具有权限
     */
    public boolean havePermission() {
        Context context = getContext();
        if (context != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                return context.checkSelfPermission(Manifest.permission.CAMERA) == PERMISSION_GRANTED;
            }
            return false;
        }
        return false;
    }
}
